/**
 * Copyright (c) 2011 Technical Centre Radio Systems Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ua.tcrs.tabula.startup.impl;

import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class HttpCachedLibraryLoader extends PathLibraryLoader {
	private String urlBase;
	
	public HttpCachedLibraryLoader( String path, String url ) {
		super( path );
		if ( !url.endsWith("/") ) url = url+'/';
		urlBase = url;
	}
	public String getURLBase() { return urlBase; }
	public ClassLoader getLoader( String name, String version ) throws IOException {
		try {
			return super.getLoader( name, version );
		} catch ( FileNotFoundException e ) {
			File dir = new File( getPath() );
			if ( !dir.exists() ) dir.mkdir(); 
			String libFileName = name + (version.equals("")?"":"-"+version) + ".jar";
			
			URL url = new URL( urlBase + libFileName );
			URLConnection tmpURLCon = url.openConnection();
			InputStream inStreamTmp = tmpURLCon.getInputStream();
			FileOutputStream outStreamTmp = new FileOutputStream( getPath() + libFileName + ".tmp" );
			int c;
			while((c = inStreamTmp.read()) != -1) { outStreamTmp.write(c); }
			inStreamTmp.close();
			outStreamTmp.close();
			
			File oldFile = new File( getPath() + libFileName);
			if ( oldFile.exists() ) oldFile.delete();
			File newFile = new File( getPath() + libFileName + ".tmp");
			newFile.renameTo( oldFile );
			
			return super.getLoader( name, version );
		}
	}
}
